#!/usr/bin/env python3
"""
简化的MCP Stdio服务器 - 仅用于测试MCP协议连接
跳过数据库初始化，直接启动MCP协议处理
"""

import asyncio
import sys
import argparse
from pathlib import Path

from loguru import logger

from src.config import load_config
from src.mcp.protocol import MCPProtocol
from src.mcp.stdio_handler import StdioHandler


class SimpleMCPServer:
    """简化的MCP服务器，不依赖数据库"""
    
    def __init__(self, config: dict):
        self.config = config
        self.protocol = MCPProtocol(config)
        
    async def initialize(self):
        """初始化服务器"""
        # 注册一些基本工具用于测试
        await self.protocol.register_tool(
            "echo",
            "Echo back the input",
            {
                "type": "object",
                "properties": {
                    "message": {
                        "type": "string",
                        "description": "Message to echo back"
                    }
                },
                "required": ["message"]
            },
            self._echo_handler
        )
        
    async def _echo_handler(self, arguments: dict) -> dict:
        """Echo工具处理器"""
        message = arguments.get("message", "")
        return {
            "content": [
                {
                    "type": "text",
                    "text": f"Echo: {message}"
                }
            ]
        }
        
    async def handle_message(self, message: dict) -> dict:
        """处理MCP消息"""
        return await self.protocol.handle_message(message)


async def start_simple_stdio_server(config: dict):
    """启动简化的Stdio服务器"""
    # 创建简化的MCP服务器
    mcp_server = SimpleMCPServer(config)
    await mcp_server.initialize()
    
    # 创建Stdio处理器
    stdio_handler = StdioHandler(mcp_server, config)
    
    logger.info("启动简化的Stdio MCP服务器")
    await stdio_handler.start()


def setup_logging(config: dict):
    """配置日志"""
    log_config = config.get('logging', {})
    
    # 移除默认处理器
    logger.remove()
    
    # 添加控制台处理器
    logger.add(
        sys.stderr,
        level=log_config.get('level', 'INFO'),
        format=log_config.get('format', '{time} | {level} | {message}'),
        colorize=True
    )


async def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='简化的MCP Stdio服务器')
    parser.add_argument(
        '--config', 
        default='config',
        help='配置文件目录路径'
    )
    
    args = parser.parse_args()
    
    # 加载配置
    try:
        config = load_config(args.config)
        setup_logging(config)
        logger.info("简化MCP服务器启动")
    except Exception as e:
        print(f"配置加载失败: {e}")
        sys.exit(1)
    
    # 启动简化的stdio服务器
    try:
        await start_simple_stdio_server(config)
    except KeyboardInterrupt:
        logger.info("收到中断信号，正在关闭服务器...")
    except Exception as e:
        logger.error(f"服务器启动失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    asyncio.run(main())